package org.tomcat.unit3;

import javax.servlet.ServletException;
import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpProcessor {

    HttpConnector connector;

    HttpRequest request;

    HttpResponse response;

    public HttpProcessor(HttpConnector connector) {
        this.connector = connector;
    }

    public void process(Socket socket) {
        InputStream input = null;
        OutputStream output = null;
        try {
            // TODO 代码逻辑不完整
            input = socket.getInputStream();
            output = socket.getOutputStream();
            request = new HttpRequest(input);
            response = new HttpResponse(output);
            response.setRequest(request);
            parseRequest(input, output);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseRequest(InputStream input, OutputStream output)
            throws IOException, ServletException {
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
        String requestLine = inputReader.readLine();
        String[] requests = requestLine.split("\\s+");
        // TODO 使用 BufferdReader 来完成相同的逻辑
        String method = requests[0];
        String uri = requests[1];
        String protocol = requests[2];
        if (method.length() < 1) {
            throw new ServletException("Missing HTTP request method");
        } else if (uri.length() < 1) {
            throw new ServletException("Missing HTTP request URI");
        }

        int question = uri.indexOf("?");
        if (question >= 0) {
            request.setQueryString(uri.substring(question + 1));
            uri = uri.substring(0, question);
        } else {
            request.setQueryString(null);
        }

        if (!uri.startsWith("/")) {
            int pos = uri.indexOf("://");
            if (pos != -1) {
                uri = "";
            } else {
                uri = uri.substring(pos);
            }
        }

        String match = ";jsessionid";
        int semicolon = uri.indexOf(match);
        if (semicolon >= 0) {
            String rest = uri.substring(semicolon + match.length());
            int semicolon2 = rest.indexOf(";");
            if (semicolon2 >= 0) {
                request.setRequestedSessionId(rest.substring(0, semicolon2));
            } else {
                request.setRequestedSessionId(rest);
                rest = "";
            }
            request.setRequestedSessionURL(true);
            uri = uri.substring(0, semicolon) + rest;
        } else {
            request.setRequestedSessionId(null);
            request.setRequestedSessionURL(false);
        }

        String normalizedUri = normalize(uri);
        ((HttpRequest) request).setMethod(method);
        request.setProtocol(protocol);
        if (normalizedUri != null) {
            ((HttpRequest) request).setRequestURI(normalizedUri);
        } else {
            ((HttpRequest) request).setRequestURI(uri);
        }
        if (normalizedUri == null) {
            throw new ServletException("Invalid URI" + uri +",");
        }
        parseHeaders(inputReader);
    }

    public void parseHeaders(BufferedReader inputReader) throws IOException {
        String line;
        Map<String,String> headers = new HashMap<String,String>();
        do {
            line = inputReader.readLine();
            if (line != null && line.length() > 0) {
                String[] lineArr = line.split(":");
                headers.put(lineArr[0], lineArr[1]);
            }
        } while (line != null && line.length() > 0);
        request.setHeaders(headers);
    }

    /**
     * 对 uri 进行修正
     * @param uri
     * @return
     */
    public String normalize(String uri) {
        // TODO 缺少相应的逻辑
        return uri;
    }
}
